/*******************************************************************************
 * Copyright 2009 
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *   http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 ******************************************************************************/
/**
 * Place holder for copyright, needs to be replaced before release.
 */
package com.softao.ming.gwt.core.internal.runtime.client;

import java.util.HashMap;
import java.util.Map;

import com.google.gwt.xml.client.Document;
import com.google.gwt.xml.client.Element;
import com.google.gwt.xml.client.NodeList;
import com.google.gwt.xml.client.XMLParser;
import com.softao.ming.gwt.core.runtime.client.application.IExtensionPoint;
import com.softao.ming.gwt.core.runtime.client.application.IExtensionRegistry;

/**
 * Implementation of this {@link IExtensionRegistry}.
 */
public class ExtensionRegistry implements IExtensionRegistry {

	private final Map<String, IExtensionPoint> mExtensionPoionts;
	
	/**
	 * 
	 */
	public ExtensionRegistry() {
		mExtensionPoionts = new HashMap<String, IExtensionPoint>();
	}
	
	/**
	 * This is called by the bootstrap only.
	 * 
	 * @param pluginManifest
	 */
	public void registerPlugin(String pluginManifest) {
		Document document = XMLParser.parse(pluginManifest);
		Element rootElement = document.getDocumentElement();
		NodeList extensionNodeList = rootElement.getElementsByTagName("extension");
		if (extensionNodeList != null && extensionNodeList.getLength() > 0) {
			for (int i = 0; i < extensionNodeList.getLength(); i++) {
				registerExtension((Element)extensionNodeList.item(i));
			}
		}
	}
	
	private void registerExtension(Element extensionElement) {
		String extensionPointId = extensionElement.getAttribute("point");
		if (!mExtensionPoionts.containsKey(extensionPointId)) {
			ExtensionPoint ep = new ExtensionPoint(extensionElement);
			mExtensionPoionts.put(ep.getUniqueIdentifier(), ep);
		}
		ExtensionPoint ep = (ExtensionPoint)mExtensionPoionts.get(extensionPointId);
		Extension extension = new Extension(ep, extensionElement);
		ep.addExtension(extension);
	}
	
	@Override
	public IExtensionPoint getExtensionPoint(String extensionPointId) {
		return mExtensionPoionts.get(extensionPointId);
	}

	@Override
	public IExtensionPoint[] getExtensionPoints() {
		return mExtensionPoionts.values().toArray(new IExtensionPoint[mExtensionPoionts.size()]);
	}

}
